#!/usr/bin/env bash

# Test monorepo task name conflicts and resolution
export MISE_EXPERIMENTAL=1

# Create monorepo root with a "build" task
cat <<EOF >mise.toml
experimental_monorepo_root = true

[tasks.build]
run = 'echo "root build"'
EOF

# Create project with also a "build" task
mkdir -p projects/frontend
cat <<EOF >projects/frontend/mise.toml
[tasks.build]
run = 'echo "frontend build"'
EOF

mise trust

# Test 1: Monorepo root task must use // prefix
echo "=== Test 1: Root task must use // prefix ==="
output=$(mise run '//:build' 2>&1)
if echo "$output" | grep -q "root build"; then
	echo "SUCCESS: Root task runs with // prefix"
else
	echo "ERROR: Expected 'root build' in output"
	echo "Output: $output"
	exit 1
fi

# Test 1b: Bare name at root should work the same as :build
echo "=== Test 1b: Bare name 'build' should run root task ==="
assert_contains "mise run build" "root build"

# Test 2: Monorepo path runs specific task
echo "=== Test 2: Prefixed path runs specific task ==="
output=$(mise run '//projects/frontend:build' 2>&1)
if echo "$output" | grep -q "frontend build"; then
	echo "SUCCESS: Monorepo path runs specific task"
else
	echo "ERROR: Expected 'frontend build' in output"
	echo "Output: $output"
	exit 1
fi

# Test 3: From subdirectory, :task syntax runs local task
echo "=== Test 3: From subdirectory :task runs local task ==="
cd projects/frontend
output=$(mise run ':build' 2>&1)
# From subdirectory, :task should run local task
if echo "$output" | grep -q "frontend build"; then
	echo "SUCCESS: From subdirectory :task runs local task"
else
	echo "ERROR: Expected 'frontend build' from subdirectory with :task"
	echo "Output: $output"
	exit 1
fi
cd ../..

# Test 4: Tasks list shows both with full paths
echo "=== Test 4: Tasks list shows both ==="
output=$(mise tasks ls --all 2>&1)
if echo "$output" | grep -q "//:build" && echo "$output" | grep -q "//projects/frontend:build"; then
	echo "SUCCESS: Both tasks visible in list"
else
	echo "ERROR: Expected both tasks in list"
	echo "Output: $output"
	exit 1
fi
